package com.nand.module.function.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.SimpleCallback;
import com.lzy.okgo.model.HttpParams;
import com.nand.library.base.base.BaseFragment;
import com.nand.library.base.bean.ResponseBean;
import com.nand.library.base.http.MyCallback;
import com.nand.library.base.http.OkGoUtils;
import com.nand.library.base.utils.SpUtils;
import com.nand.module.function.FunctionApp;
import com.nand.module.function.R;
import com.nand.module.function.adapter.EpairListAdapter;
import com.nand.module.function.adapter.EquipmentAdapter;
import com.nand.module.function.bean.EpairListBean;
import com.nand.module.function.bean.EqDatailBean;
import com.nand.module.function.bean.ManageBean;
import com.nand.module.function.constant.URL;
import com.nand.module.function.ui.EpairDetailsActivity;
import com.nand.module.function.ui.EpairListActivity;
import com.nand.module.function.ui.EqListActivity;
import com.nand.module.function.utils.LogUtils;
import com.nand.module.function.utils.MsgUtil;
import com.nand.module.function.utils.SpacesItemDecoration;
import com.nand.module.function.view.CustomPartShadowPopupView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;


import java.util.ArrayList;
import java.util.List;

/**
 * created by 86185
 * on 2019/12/24
 */
public class EpairListFragment extends BaseFragment {

    private RecyclerView mRecycler;
    private EpairListAdapter mRecyclerAdapter;
    private int type;
    private List<EpairListBean.DataListBean> mList = new ArrayList<>();
    private SmartRefreshLayout swipeRefres;
    private HttpParams paramsPost;
    private int page;//加载页数
    private LinearLayout llEmpty;
    private int userId;

    private CheckBox cbType;
    private CheckBox cbSort;
    private int resultPosition = 0;//默认选择position
    private int typePosition = 0;//默认选择position
    private String[] resultData;//数据源
    private String[] typeData;//数据源
    private CustomPartShadowPopupView popupViewResult;
    private CustomPartShadowPopupView popupViewType;
    public static EpairListFragment newInstance(int page) {
        EpairListFragment fragment = new EpairListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("TYPE", page);
        fragment.setArguments(bundle);
        return fragment;
    }
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_epair_list;
    }

    @Override
    protected void initView(View view) {
        mRecycler = view.findViewById(R.id.recycler);
        type = getArguments().getInt("TYPE");
        swipeRefres = view.findViewById(R.id.swipe_refres);
        page = 1;
        userId = SpUtils.readInt(getActivity(), "userId", 0);
        llEmpty = view.findViewById(R.id.ll_empty);
        cbType = view.findViewById(R.id.cb_result);
        cbSort = view.findViewById(R.id.cb_type);
        resultData = getResources().getStringArray(R.array.abnormal_grade_list);
        typeData = getResources().getStringArray(R.array.abnormal_type_list);

        llEmpty.setVisibility(View.GONE);
        swipeRefres.setEnableRefresh(true);//是否启用下拉刷新功能
        swipeRefres.setEnableLoadMore(true);//是否启用上拉加载功能
        swipeRefres.setEnableAutoLoadMore(true);//是否启用列表惯性滑动到底部时自动加载更多
        swipeRefres.setRefreshHeader(new ClassicsHeader(getActivity()));
        swipeRefres.setRefreshFooter(new ClassicsFooter(getActivity()));

        swipeRefres.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //刷新需要执行操作
                page = 1;
                paramsPost = new HttpParams();
                paramsPost.put("current", String.valueOf(page));
                paramsPost.put("size", "10");
                //initHttpData(false);
                selectListCondition(false);
            }
        });
        swipeRefres.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //刷新需要执行操作
                page++;
                paramsPost = new HttpParams();
                paramsPost.put("current", String.valueOf(page));
                paramsPost.put("size", "10");
                //initHttpData(false);
                selectListCondition(false);
            }
        });
        initData();

        cbType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupViewResultList(view,resultData,getResources().getString(R.string.sx_yclx));
            }
        });
        cbSort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupViewTypeList(view,typeData,getResources().getString(R.string.sx_cpfl));
            }
        });
    }

    /**
     *  @author ljp
     *  @time   14:11
     *  @describe 弹出筛选条件list()
     */
    private void showPopupViewResultList(View view, String[] data, final String value){
        if(popupViewResult==null){
            popupViewResult = (CustomPartShadowPopupView) new XPopup.Builder(getContext())
                    .atView(view)
                    .autoOpenSoftInput(true)
                    .setPopupCallback(new SimpleCallback() {
                        @Override
                        public void onShow() {
                        }
                        @Override
                        public void onDismiss() {
                            cbType.setChecked(false);
                        }
                    })
                    .asCustom(new CustomPartShadowPopupView(getContext()));
            popupViewResult.setStringData(data, null);
            popupViewResult .setCheckedPosition(resultPosition);
            popupViewResult .setOnSelectListener(new CustomPartShadowPopupView.OnSelectListener() {
                @Override
                public void onSelect(int position, String text) {
                    resultPosition = position;
                    cbType.setText(position == 0 ?value:text);
                    page = 1;
                    selectListCondition(true);
                }
            });
        }
        popupViewResult.show();
    }

    /**
     *  @author ljp
     *  @time   10:06
     *  @describe 根据筛选条件查询数据
     */
    private void selectListCondition(boolean isFirst){
        Log.e("EpairListFragment", "selectListCondition: ---resultPosition----"+resultPosition);
        paramsPost.clear();
        paramsPost.put("current", String.valueOf(page));
        paramsPost.put("size", "10");
        if (resultPosition > 0) {
            if (typePosition > 0) {
                paramsPost.put("prodAnoType", cbType.getText().toString());
                paramsPost.put("productType", String.valueOf(typePosition - 1));
            } else {
                paramsPost.put("prodAnoType", cbType.getText().toString());
            }
        } else {
            if (typePosition > 0) {
                paramsPost.put("productType", String.valueOf(typePosition - 1));
            }
        }
        initHttpData(isFirst);
    }

    /**
     *  @author ljp
     *  @time   14:11
     *  @describe 弹出筛选条件list()
     */
    private void showPopupViewTypeList(View view,String[] data,final String value){
        if(popupViewType==null){
            popupViewType = (CustomPartShadowPopupView) new XPopup.Builder(getContext())
                    .atView(view)
                    .autoOpenSoftInput(true)
                    .setPopupCallback(new SimpleCallback() {
                        @Override
                        public void onShow() {
                        }
                        @Override
                        public void onDismiss() {
                            cbSort.setChecked(false);
                        }
                    })
                    .asCustom(new CustomPartShadowPopupView(getContext()));
            popupViewType.setStringData(data, null);
            popupViewType .setCheckedPosition(typePosition );
            popupViewType .setOnSelectListener(new CustomPartShadowPopupView.OnSelectListener() {
                @Override
                public void onSelect(int position, String text) {
                    typePosition = position;
                    cbSort.setText(position == 0 ? value:text);
                    selectListCondition(true);
                }
            });
        }
        popupViewType.show();
    }
    /**
     *  @author ljp
     *  @time   10:25
     *  @describe 新增异常后刷新页面
     */
    public void setSwipeRefres(){
        page = 1;
        swipeRefres.autoRefresh();
    }

    private void initData() {
        mRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerAdapter = new EpairListAdapter(getActivity(), 1);
        final int space = 20;
        mRecycler.addItemDecoration(new SpacesItemDecoration(space));
        mRecycler.setAdapter(mRecyclerAdapter);

        mRecyclerAdapter.setOnItemClickListener(new EpairListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                int state = mList.get(position).getState();
                String abnormalId = mList.get(position).getAbnormalId();
                Intent intent = null;
                Bundle bundle = null;
                switch (state){
                    case 0:  //待处理
                        int userID = mList.get(position).getUserID();

                        intent = new Intent(getActivity(), EpairDetailsActivity.class);
                        bundle = new Bundle();
                        if (userId == userID){
                            bundle.putInt("code", 102);
                        }else {
                            bundle.putInt("code", 105);
                        }

                        bundle.putString("abnormalId", abnormalId);
                        intent.putExtras(bundle);
                        break;
                    case 1:  //待确认
                        int i = mList.get(position).getfUserCreator();
                        intent = new Intent(getActivity(), EpairDetailsActivity.class);
                        bundle = new Bundle();
                        if (userId == i){
                            bundle.putInt("code", 103);
                        }else {
                            bundle.putInt("code", 105);
                        }

                        bundle.putString("abnormalId", abnormalId);
                        intent.putExtras(bundle);
                        break;
                    case 3:  //待提交
                        int fUserCreator = mList.get(position).getfUserCreator();
                        intent = new Intent(getActivity(), EpairDetailsActivity.class);
                        bundle = new Bundle();
                        if (userId == fUserCreator){
                            bundle.putInt("code", 104);
                        }else {
                            bundle.putInt("code", 105);
                        }

                        bundle.putString("abnormalId", abnormalId);
                        intent.putExtras(bundle);
                        break;
                    case 2:  //关闭
                    case 4: //终止
                        intent = new Intent(getActivity(), EpairDetailsActivity.class);
                        bundle = new Bundle();
                        bundle.putInt("code", 105);
                        bundle.putString("abnormalId", abnormalId);
                        intent.putExtras(bundle);
                        break;
                }
                if (null != intent){
                    startActivityForResult(intent,1001);
                }
                // startActivity(new Intent(getActivity(), EpairDetailsActivity.class));
            }
        });


        paramsPost = new HttpParams();
        paramsPost.put("current", "1");
        paramsPost.put("size", "10");
        initHttpData(true);
    }

    private void initHttpData(final boolean isFirst) {
        LogUtils.e("typeabcd==initHttpData==="+paramsPost);
        if (1 == type)
            paramsPost.put("userId", userId);

        OkGoUtils.getInstance().post(getActivity(), URL.EPAIR_LIST, paramsPost, 1, true, new MyCallback() {
            @Override
            public void onSuccess(ResponseBean response, int id) {
                if (200 == response.getCode()){
                    String s = response.getDataInfo().toString();
                    swipeRefres.finishLoadMore();

                    LogUtils.e("abcd====="+s);
                    LogUtils.e("abcd====="+isFirst);
                    LogUtils.e("pageabcd====="+page);
                    if (!isFirst)
                        swipeRefres.finishRefresh();


                    EpairListBean listBeans = JSON.parseObject(s, EpairListBean.class);
                    List<EpairListBean.DataListBean> data = listBeans.getDataList();
                    LogUtils.e("abcd====="+data.size());
                    if (page != 1) {
                        if (data == null || data.size() == 0) {
                            swipeRefres.finishLoadMoreWithNoMoreData();
                        }
                    } else {
                        if (data.size() == 0) {
                            llEmpty.setVisibility(View.VISIBLE);
                        } else {
                            llEmpty.setVisibility(View.GONE);
                        }
                        mList.clear();
                    }
                    for (EpairListBean.DataListBean bean : data) {
                        mList.add(bean);
                    }
                    mRecyclerAdapter.setData(mList);
                }else {
                    //  MsgUtil.toast(response.getMsg());
                }

            }

            @Override
            public void onError(Throwable e, int id) {

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.e("fragmentfragmentabc====="+requestCode +"===="+resultCode);
        if (1001 == requestCode){
            paramsPost = new HttpParams();
            paramsPost.put("current", page);
            paramsPost.put("size", "10");
            selectListCondition(true);
            //initHttpData(true);

        }

    }
}
